// 腾讯云对象存储服务接口

package misc

import (
	"bytes"
	"crypto/md5"
	"dhfshop/controllers/base"
	"dhfshop/models/misc"
	"dhfshop/service/tcos"
	"dhfshop/utils/imageCompress"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"
	//"dhfshop/service/img/resize"
	"github.com/satori/go.uuid"
)

var uploadTmpFilePath string = "static/uploadtmp"
var quality = 80

//
type TcosFileController struct {
	base.BaseController
}

// 上传附件
func (this *TcosFileController) Create() {
	//
	cosAppId := beego.AppConfig.String("CosAppId")
	cosRegion := beego.AppConfig.String("CosRegion")
	cosSecretId := beego.AppConfig.String("CosSecretId")
	cosSecretKey := beego.AppConfig.String("CosSecretKey")
	cosReturnUrl := beego.AppConfig.String("CosReturnUrl")
	//
	companyId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	file, fileHeader, err := this.GetFile("wxfile")
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	contentType := fileHeader.Header.Get("Content-Type")
	originalFilename := fileHeader.Filename
	ext := path.Ext(originalFilename)
	clientUId := uuid.NewV4().String() + ext
	attachment := misc.Attachment{
		CompanyId:    companyId,
		CreatorId:    curUserId,
		UUId:         clientUId,
		OriginalName: originalFilename,
		Mime:         contentType,
	}
	//beego.Debug("CreateAttachment companyId:", companyId)
	buf, err := ioutil.ReadAll(file)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	attachment.Md5Hash = this.getFileMd5(buf)
	if oldAttachment, err := misc.GetAttachByMd5Hash(attachment.Md5Hash); err == nil {
		//当前用户的重复上传，返回错误提示
		if ok := misc.CheckAttachHashExist(attachment.CreatorId, attachment.Md5Hash); ok {
			beego.Debug("The same user file MD5 is exist:", attachment.Md5Hash)
			this.Data["json"] = oldAttachment
			this.ServeJSON()
		} else { //非当前用户的重复上传，不需要存储文件，但需要写入记录
			beego.Debug("Not the same user file MD5 is exist:", attachment.Md5Hash)
			attachment.Size = oldAttachment.Size
			attachment.URL = oldAttachment.URL
			if attachment.Id, err = misc.CreateAttachment(&attachment); err != nil {
				this.ServeError(err.Error())
				return
			}
			this.Data["json"] = attachment
			this.ServeJSON()
		}
	}
	fileLen, err := file.Seek(0, os.SEEK_END)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	_, err = file.Seek(0, os.SEEK_SET)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	attachment.Size = uint64(fileLen)
	file.Close()
	//
	if _, err := os.Stat(uploadTmpFilePath); os.IsNotExist(err) {
		os.Mkdir(uploadTmpFilePath, 0777)
	}
	localPath := uploadTmpFilePath + "/" + attachment.UUId

	data, err := ioutil.ReadAll(file)
	if err != nil {
		this.ServeError(err.Error())
		return
	}

	//图片压缩
	extFile := filepath.Ext(fileHeader.Filename)
	extf := strings.ToLower(extFile)
	if extf == ".png" || extf == ".jpeg" || extf == ".jpg" {
		t1 := bytes.NewReader(data)
		t2 := bytes.NewReader(data)
		err = imageCompress.ImageCompress(t1, t2, localPath, quality, extf[1:])
		if err != nil {
			//fmt.Println("生成缩略图失败")
			this.ServeError(err.Error())
			return
		}
	} else {
		//视频
		err = this.SaveToFile("wxfile", localPath)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}

	/*
		outFile := uploadTmpFilePath + "/" + uuid.NewV4().String() + ext
		err = resize.ResizePro(localPath, outFile)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	*/

	outFile := localPath
	cosPath := "goimg" + "/" + attachment.UUId

	attachment.URL, err = tcos.UploadObj(cosAppId, cosRegion, cosSecretId, cosSecretKey, cosPath, outFile, cosReturnUrl)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if attachment.Id, err = misc.CreateAttachment(&attachment); err != nil {
		this.ServeError(err.Error())
		return
	}
	this.Data["json"] = attachment
	this.ServeJSON()
}

// @Title 删除附件
func (this *TcosFileController) Delete() {
	uuid := this.GetString("uuid")
	attachment, err := misc.GetAttachmentByUuid(uuid)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if err = misc.DeleteAttachmentByUuid(uuid); err != nil {
		this.ServeError(err.Error())
		return
	}
	//
	cosAppId := beego.AppConfig.String("CosAppId")
	cosRegion := beego.AppConfig.String("CosRegion")
	cosSecretId := beego.AppConfig.String("CosSecretId")
	cosSecretKey := beego.AppConfig.String("CosSecretKey")
	//
	kv := strings.Split(attachment.URL, "myqcloud.com/")
	cosPath := kv[1]
	err = tcos.DeleteObj(cosAppId, cosRegion, cosSecretId, cosSecretKey, cosPath)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	this.ServeJSON()
}

func (this *TcosFileController) getFileMd5(buf []byte) string {
	hash := md5.New()
	hash.Write(buf)
	return fmt.Sprintf("%x", hash.Sum(nil))
}
